#include <game/Root.h>
#include <game/ScreenManager.h>
#include <game/flow/Manager.h>
#include "services/DelayedActionServiceImpl.h"
#include <game/services/ApplicationService.h>

ARELLO_GAME_NAMESPACE_DECL_START
	
Root::Root(liba::lib3d::Application* app)
	: screenManager(0)
	, application(app)
{
	std::auto_ptr<ScreenManager> localScreenManager(new ScreenManager());
	localScreenManager->SetGame(this);
	this->screenManager = localScreenManager.get();

	this->Register<services::ScreenSwitcher>(
		std::auto_ptr<services::ScreenSwitcher>(localScreenManager.release()));

	LIBA_ASSERT(this->application);
	std::auto_ptr<services::ApplicationService> applicationService(new services::ApplicationService(this->application));
	this->Register<services::ApplicationService>(applicationService);
	

	std::auto_ptr<DelayedActionServiceImpl> localDelayedActionService(new DelayedActionServiceImpl());
	this->delayedActionService = localDelayedActionService.get();

	this->Register<services::DelayedActions>(
		std::auto_ptr<services::DelayedActions>(localDelayedActionService.release()));
}

Root::~Root()
{
	this->screenManager->Shutdown();
}

void Root::SetFlowManager(std::auto_ptr<flow::Manager> value)
{
	this->flowManager = value;
	this->flowManager->SetSelectorFactory(this->selectorFactory);
	this->flowManager->SetTriggerFactory(this->triggerFactory);
	this->flowManager->SetRoot(this);
	this->screenManager->SetFlowManager(flowManager.get());
}

void Root::SetSelectorFactory(const flow::SelectorFactory& value)
{
	this->selectorFactory = value;

	if (this->flowManager.get())
		this->flowManager->SetSelectorFactory(this->selectorFactory);
}

void Root::SetTriggerFactory(const flow::TriggerFactory& value)
{
	this->triggerFactory = value;

	if (this->flowManager.get())
		this->flowManager->SetTriggerFactory(this->triggerFactory);
}

bool Root::LifeCycle(time_float dt)
{
	delayedActionService->Perform(dt);
	if(debugManger.get())
		debugManger->LifeCycle(dt);
	return screenManager->LifeCycle(dt);
}

void Root::render(liba::lib3d::hard::Hardware* hardware)
{
//	if (debugManger.get())
//	{
//		screenManager->render(hardware, debugManger);
//		//return;
//	}
	//debugManger->render(hardware);
	screenManager->render(hardware, debugManger.get());
	
}

ARELLO_GAME_NAMESPACE_DECL_END